import tcpClient from "@/utils/tcpClient.js";
import bufferUtils from "@/utils/bufferUtils.js";
export default {
	dataCallback:null,
    tcpPlugin: null,
    connected: false,
    reconnecting: false,
    reconnectTimer: null,
    heartbeatTimer: null,
    maxReconnectAttempts: 5,
    reconnectAttempts: 0,
    lastDataTime: 0,
    lastHeartbeatTime: 0,
    heartbeatSequence: 1,
    pageInstanceId: null,
    isPageActive: false,
    pendingMessages: [],
    dataBuffer: "",
    dataHandlers: [],
    currentIp: "",
    currentPort: 0,
    
    // 初始化TCP插件
    init(pageInstanceId) {
        if (this.tcpPlugin && this.pageInstanceId === pageInstanceId) return;
        
        this.pageInstanceId = pageInstanceId;
        this.isPageActive = true;
        this.pendingMessages = [];
        this.dataBuffer = "";
        this.dataHandlers = [];
        
        this.tcpPlugin = uni.requireNativePlugin('tcpclientbytes');
        this.tcpPlugin.initialize(res => {
            console.log(res);
        }, err => {
            console.log(err);
        });
               
		// 使用箭头函数保存回调，避免this指向问题
		this.dataCallback = (data) => {
			this.onDataReceived(data);
			// 只注册一次回调函数
			this.tcpPlugin.setDataByteArrayBase64StrCallback(this.dataCallback);
		};
        // 只注册一次回调函数
        this.tcpPlugin.setDataByteArrayBase64StrCallback(this.dataCallback);
        
        console.log('TCP客户端初始化完成，页面实例ID: ' + pageInstanceId);
    },
    onDataReceived(data){
		this.lastDataTime = Date.now();
		// var str=tcpClient.encodeBase64String(data)
		// console.log(str)
		if (this.isPageActive) {
			console.log("接收到数据byte[] 转base64的字符串: " + data);
			this.processReceivedData(data);
		} else {
			this.pendingMessages.push(data);
			console.log("页面不活跃，暂存消息，共暂存: " + this.pendingMessages.length + "条");
		}
	},
    // 处理接收到的数据
    processReceivedData(base64Data) {
        try {
            const binaryData = atob(base64Data);
            const arrayBuffer = new ArrayBuffer(binaryData.length);
            const uintArray = new Uint8Array(arrayBuffer);
            
            for (let i = 0; i < binaryData.length; i++) {
                uintArray[i] = binaryData.charCodeAt(i);
            }
			// var uintArray2=tcpClient.javaCompatibleBase64Decode(base64Data)
			console.log(uintArray)
            // console.log(uintArray2)
            // this.dataBuffer=[...this.dataBuffer,...uintArray];
			 this.handleTcpData(uintArray)
			// this.dataBuffer+=base64Data
			// console.log( this.dataBuffer)
            // this.parseDataPackets();
        } catch (error) {
            console.error('处理接收到的数据时出错:', error);
            this.logError('processReceivedData', error);
            this.dataBuffer =new Uint8Array(0);
        }
    },
    // /**
    //  * 处理TCP数据接收的示例函数
    //  * @param {Uint8Array} receivedData - 接收到的数据
    //  */
   handleTcpData(receivedData) {
	     console.log(receivedData)
  // 假设我们有一个全局缓冲区
  this.dataBuffer = this.dataBuffer || new Uint8Array(0);
  
  // 解析数据包
  const { remainingBuffer, packets, isComplete } =bufferUtils.getJsonPackets(this.dataBuffer, receivedData);
  console.log(remainingBuffer)
  // 更新缓冲区
  this.dataBuffer = remainingBuffer;
  
  // 处理解析出的数据包
  packets.forEach(packet => {
    // 处理业务逻辑
    console.log("解析到数据包:", packet);
  });
  
  // 可以根据isComplete判断是否所有JSON都已完整解析
  if (!isComplete) {
    console.log("存在未完成的JSON，等待下一个数据包");
  }
    },

    // 处理单个数据包
    handlePacket(packetData) {
		// 业务逻辑处理
		console.log("收到数据包:", packet);
        try {
            const jsonData = JSON.parse(packetData);
            console.log('解析数据包:', jsonData);
            this.triggerEvent('dataReceived', jsonData);
            this.dataHandlers.forEach(handler => handler(jsonData));
        } catch (error) {
            console.error('解析JSON数据包时出错:', error);
            this.logError('handlePacket', error);
            this.dataHandlers.forEach(handler => handler({ rawData: packetData, error: error.message }));
        }
    },
    
    // 添加数据处理器
    addDataHandler(handler, event = 'dataReceived') {
        if (typeof handler === 'function') {
            this.dataHandlers.push({ handler, event });
        }
    },
    
    // 移除数据处理器
    removeDataHandler(handler) {
        if (typeof handler === 'function') {
            this.dataHandlers = this.dataHandlers.filter(h => h.handler !== handler);
        }
    },
    
    // 触发事件
    triggerEvent(eventName, data) {
        this.dataHandlers.forEach(h => {
            if (h.event === eventName && typeof h.handler === 'function') {
                h.handler(data);
            }
        });
    },
    
    // 连接到服务器
    connect(ip, port, timeout = 5000) {
        // ip = "192.168.1.228"; // 测试IP
        ip ="60.10.207.222";
        if (!this.tcpPlugin || !this.isPageActive) {
            console.error('TCP客户端未初始化或页面不活跃');
            return;
        }
        
        console.log(`尝试连接到 ${ip}:${port}`);
        this.currentIp = ip;
        this.currentPort = port;
        
        // 添加连接超时处理
        const timeoutId = setTimeout(() => {
            if (!this.connected) {
                console.error('连接超时');
                this.handleConnectionError(ip, port, timeout);
            }
        }, timeout + 1000);
        
        this.tcpPlugin.connect(
            ip, port, timeout,
            (res) => {
                clearTimeout(timeoutId);
                if (!this.isPageActive) return;
                
                console.log('连接成功:', res);
                this.connected = true;
                this.reconnectAttempts = 0;
                this.clearReconnectTimer();
                this.sendInitialData();
                this.startHeartbeat();
                this.triggerEvent('connectionEstablished', { host: ip, port });
            },
            (err) => {
                clearTimeout(timeoutId);
                if (!this.isPageActive) return;
                
                console.error('连接失败:', err);
                this.addLog('连接失败: ' + err);
                
                // 解析错误类型
                let errorType = '未知错误';
                if (err.includes('Connection refused')) {
                    errorType = '服务器拒绝连接';
                } else if (err.includes('timeout')) {
                    errorType = '连接超时';
                } else if (err.includes('Unknown host')) {
                    errorType = '未知主机';
                }
                
                this.addLog('错误类型: ' + errorType);
                this.handleConnectionError(ip, port, timeout);
                this.triggerEvent('connectionFailed', { error: err });
            }
        );
    },
    
    // 发送初始数据
    sendInitialData() {
        const jsonData = {
            request: 'CONNECT',
            timestamp: new Date().getTime(),
            clientInfo: {
                appVersion: uni.getSystemInfoSync().appVersion,
                deviceId: uni.getSystemInfoSync().deviceId
            }
        };
        this.sendData(jsonData);
    },
    
    // 发送数据
    sendData(jsonData) {
        if (!this.tcpPlugin || !this.connected || !this.isPageActive) {
            console.error('TCP客户端未连接或页面不活跃');
            return;
        }
        
        try {
            const jsonStr = JSON.stringify(jsonData);
            const checksum = tcpClient.crcCcitt(tcpClient.stringToByteArray(jsonStr), 0);
            const byteArray = tcpClient.buildPacketFromJson(jsonStr, checksum);
            console.log(byteArray)
            // 构建长度前缀数据包
            const lengthPrefix = byteArray.length.toString().padStart(4, '0');
            const packet = lengthPrefix + btoa(String.fromCharCode.apply(null, byteArray));
            
            this.tcpPlugin.sendBase64Str(
                packet,
                (res) => {
                    if (this.isPageActive) {
                        console.log('发送成功:', res);
                        this.triggerEvent('dataSent', { data: jsonData });
                    }
                },
                (err) => {
                    if (this.isPageActive) {
                        console.error('发送失败:', err);
                        this.connected = false;
                        this.triggerEvent('sendFailed', { error: err, data: jsonData });
                        this.handleConnectionError(this.currentIp, this.currentPort);
                    }
                }
            );
        } catch (error) {
            console.error('构建或发送数据包时出错:', error);
            this.logError('sendData', error);
            this.triggerEvent('sendError', { error, data: jsonData });
        }
    },
    
    // 心跳检测
    startHeartbeat(interval = 30000) {
        if (this.heartbeatTimer || !this.isPageActive) return;
        
        this.heartbeatTimer = setInterval(() => {
            if (this.connected && this.isPageActive) {
                const now = Date.now();
                const isTimeout = now - this.lastDataTime > interval * 1.5;
                const isHeartbeatDue = now - this.lastHeartbeatTime > interval;
                
                if (isTimeout) {
                    console.warn('心跳检测: 连接超时，尝试重连');
                    this.connected = false;
                    this.triggerEvent('connectionTimeout', { lastDataTime: this.lastDataTime });
                    this.reconnect();
                } else if (isHeartbeatDue) {
                    this.sendData({ 
                        request: 'HEARTBEAT', 
                        timestamp: now,
                        sequence: this.heartbeatSequence++
                    });
                    this.lastHeartbeatTime = now;
                }
            }
        }, interval);
    },
    
    // 停止心跳检测
    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    },
    
    // 重连机制
    reconnect() {
        if (this.reconnecting || !this.isPageActive) return;
        
        this.reconnecting = true;
        const maxAttempts = this.maxReconnectAttempts || 5;
        const delay = Math.min(30000, 1000 * Math.pow(2, this.reconnectAttempts));
        
        console.log(`尝试重新连接...第 ${this.reconnectAttempts + 1} 次，延迟 ${delay/1000} 秒`);
        
        setTimeout(() => {
            if (this.reconnectAttempts < maxAttempts && this.isPageActive) {
                this.reconnectAttempts++;
                this.connect(this.currentIp, this.currentPort);
                this.reconnecting = false;
            } else {
                console.error(`达到最大重连次数 ${maxAttempts}，放弃重连`);
                this.reconnecting = false;
                this.clearReconnectTimer();
                this.triggerEvent('reconnectFailed', {
                    attempts: this.reconnectAttempts,
                    timestamp: new Date().getTime()
                });
            }
        }, delay);
    },
    
    // 清理重连定时器
    clearReconnectTimer() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }
    },
    
    // 处理连接错误
    handleConnectionError(ip, port, timeout) {
        if (!this.isPageActive) return;
        
        this.connected = false;
        this.currentIp = ip;
        this.currentPort = port;
        
        if (!this.reconnecting && !this.reconnectTimer && this.isPageActive) {
            this.reconnect();
        }
    },
    
    // 处理页面激活
    onPageShow() {
        this.isPageActive = true;
        
        if (this.pendingMessages.length > 0) {
            console.log('页面激活，处理暂存的消息，共: ' + this.pendingMessages.length + '条');
            this.pendingMessages.forEach(data => {
                this.processReceivedData(data);
            });
            this.pendingMessages = [];
        }
        
        if (this.tcpPlugin && this.currentIp && this.currentPort && !this.connected) {
            this.connect(this.currentIp, this.currentPort);
        }
        
        this.triggerEvent('pageActivated');
    },
    
    // 处理页面隐藏
    onPageHide() {
        this.isPageActive = false;
        this.stopHeartbeat();
        this.clearReconnectTimer();
        this.triggerEvent('pageDeactivated');
    },
    
    // 处理页面销毁
    onPageDestroy() {
        this.isPageActive = false;
        this.stopHeartbeat();
        this.clearReconnectTimer();
        this.close();
        this.tcpPlugin = null;
        this.pageInstanceId = null;
        this.dataHandlers = [];
        this.triggerEvent('pageDestroyed');
    },
    
    // 关闭连接
    close() {
        if (!this.tcpPlugin || !this.isPageActive) {
            return;
        }
        
        // 停止心跳和重连
        this.stopHeartbeat();
        this.clearReconnectTimer();
        
        this.tcpPlugin.close(
            (res) => {
                if (this.isPageActive) {
                    console.log('断开连接:', res);
                    this.connected = false;
                    this.triggerEvent('connectionClosed', { reason: 'manual' });
                }
            },
            (err) => {
                if (this.isPageActive) {
                    console.error('断开失败:', err);
                    this.connected = false;
                    this.triggerEvent('connectionError', { error: err });
                }
            }
        );
    },
    
    // 统一错误处理
    logError(method, error) {
        console.error(`[TCP Client Error] Method: ${method}, Message: ${error.message}`);
        if (error.stack) console.error(error.stack);
        
        // 触发错误事件
        this.triggerEvent('error', {
            method,
            message: error.message,
            stack: error.stack
        });
    },
    
    // 检查连接状态
    isConnected() {
        return this.connected && this.isPageActive;
    },
    
    // 获取连接信息
    getConnectionInfo() {
        return {
            connected: this.connected,
            host: this.currentIp,
            port: this.currentPort,
            lastDataTime: this.lastDataTime,
            heartbeatSequence: this.heartbeatSequence,
            reconnectAttempts: this.reconnectAttempts,
            isPageActive: this.isPageActive,
            pendingMessages: this.pendingMessages.length
        };
    },
    
    // 设置配置
    setConfig(config) {
        if (typeof config !== 'object') return;
        
        // 允许配置的参数
        const allowedKeys = [
            'maxReconnectAttempts',
            'heartbeatInterval',
            'reconnectDelay',
            'timeout'
        ];
        
        Object.keys(config).forEach(key => {
            if (allowedKeys.includes(key)) {
                this[key] = config[key];
            }
        });
        
        console.log('TCP客户端配置已更新:', config);
    }
}